{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-12-02T09:28:01.401282Z",
     "start_time": "2024-12-02T09:28:01.392123Z"
    }
   },
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from torchvision import datasets, transforms\n",
    "from torch.utils.data import DataLoader\n",
    "\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')"
   ],
   "outputs": [],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T09:28:02.159197Z",
     "start_time": "2024-12-02T09:28:02.134474Z"
    }
   },
   "cell_type": "code",
   "source": [
    "data_dir=\"C:/Users/Lenovo/Desktop/深度/实验三数据集/车辆分类数据集\"\n",
    "transform = transforms.Compose([\n",
    "    transforms.Resize((64, 64)),\n",
    "    transforms.ToTensor(),\n",
    "    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n",
    "])\n",
    "\n",
    "dataset = datasets.ImageFolder(data_dir, transform=transform)\n",
    "\n",
    "dataloader = DataLoader(dataset, batch_size=32, shuffle=True,num_workers=4)\n"
   ],
   "id": "e865decc9c8ca7ad",
   "outputs": [],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T09:34:16.365431Z",
     "start_time": "2024-12-02T09:34:16.358099Z"
    }
   },
   "cell_type": "code",
   "source": [
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Net, self).__init__()\n",
    "        self.layer1 = nn.Sequential(\n",
    "            nn.Conv2d(3, 32, kernel_size=3, padding=1, dilation=2),\n",
    "            nn.BatchNorm2d(32),\n",
    "            nn.ReLU(inplace=True),\n",
    "        )\n",
    "        self.fc=nn.Linear(in_features=32, out_features=3)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        x = self.layer1(x)\n",
    "        #print(x.shape)\n",
    "        x= F.avg_pool2d(x, 62)\n",
    "        x= x.squeeze()\n",
    "        x = self.fc(x)\n",
    "        return x\n"
   ],
   "id": "d9a7ca84ba29c26b",
   "outputs": [],
   "execution_count": 29
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T09:34:17.030861Z",
     "start_time": "2024-12-02T09:34:17.020560Z"
    }
   },
   "cell_type": "code",
   "source": [
    "net = Net().to(device)\n",
    "criterion= nn.CrossEntropyLoss()\n",
    "optimizer= torch.optim.Adam(net.parameters(),lr=0.01)"
   ],
   "id": "5c5163a923a30472",
   "outputs": [],
   "execution_count": 30
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T09:34:17.541522Z",
     "start_time": "2024-12-02T09:34:17.532723Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def train_net(net,dataloader):\n",
    "    net.train()\n",
    "    train_batches=len(dataloader)\n",
    "    \n",
    "    for epoch in range(10):\n",
    "        total_loss=0\n",
    "        correct=0\n",
    "        sample_num=0\n",
    "        for batch_idx, (data, target) in enumerate(dataloader):\n",
    "            data=data.to(device).float()\n",
    "            target=target.to(device).long()\n",
    "            \n",
    "            optimizer.zero_grad()\n",
    "            output=net(data)\n",
    "            loss=criterion(output,target)\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "            \n",
    "            #print(\"Batch %d, Loss: %.4f\"%(batch_idx,loss.item()))\n",
    "            \n",
    "            total_loss+=loss.item()\n",
    "            prediction=torch.argmax(output,1)\n",
    "            correct += (prediction==target).sum().item()\n",
    "            sample_num+=len(prediction)\n",
    "            \n",
    "        \n",
    "        loss=total_loss/train_batches\n",
    "        acc=correct/train_batches\n",
    "        print('Loss: {:.4f} Acc: {:.4f}'.format(loss,acc))\n",
    "    return loss,acc\n",
    "        "
   ],
   "id": "5177c4b916abc4a3",
   "outputs": [],
   "execution_count": 31
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-12-02T09:38:38.846880Z",
     "start_time": "2024-12-02T09:34:18.405780Z"
    }
   },
   "cell_type": "code",
   "source": "train_net(net,dataloader)",
   "id": "ff99974bbaa6c361",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loss: 0.8391 Acc: 19.7442\n",
      "Loss: 0.7614 Acc: 22.0233\n",
      "Loss: 0.7215 Acc: 23.1163\n",
      "Loss: 0.6833 Acc: 23.7209\n",
      "Loss: 0.6700 Acc: 23.9535\n",
      "Loss: 0.6560 Acc: 24.7209\n",
      "Loss: 0.6375 Acc: 24.4419\n",
      "Loss: 0.6025 Acc: 24.8372\n",
      "Loss: 0.5836 Acc: 25.4884\n",
      "Loss: 0.5679 Acc: 25.8372\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(0.5678829037865927, 25.837209302325583)"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 32
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "98983969b51b0a99"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
